package com.hs.httpclient.service.impl;

import com.hs.httpclient.service.AbstractHttpRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @Author: songhao
 * @Date: 2020/11/12
 * @Description: 发送get请求的实现类
 */
public class GetMethodRquestmpl extends AbstractHttpRequest {

    static final Logger logger = LoggerFactory.getLogger(GetMethodRquestmpl.class);

    @Override
    public String requestGet(String url, Map<String, String> headerMap) throws Exception {
        logger.info("===>正在请求url:{}",url);
        String result = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try{
            httpClient = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            //设置请求的header信息
            setRequestHead(get, headerMap);
            //获取响应信息
            response = httpClient.execute(get);
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                result = entityToString(entity);
            }
            return result;
        } catch (IOException e) {
            throw e;
        }finally {
            try {
                if(httpClient != null){
                    httpClient.close();
                }
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                throw e;
            }
        }
    }

    /**
     * 获取响应实体的数据
     * @param entity
     * @return
     * @throws IOException
     */
    private static String entityToString(HttpEntity entity) throws IOException {
        String result = null;
        if(entity != null) {
            long lenth = entity.getContentLength();
            if(lenth != -1 && lenth < 2048) {
                result = EntityUtils.toString(entity,"UTF-8");
            }else {
                InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
                CharArrayBuffer buffer = new CharArrayBuffer(2048);
                char[] tmp = new char[1024];
                int l;
                while((l = reader1.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            }
        }
        return result;
    }
}
